package com.tx.logsys.controller;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.tx.logsys.mapper.BaseUserMapper;
import com.tx.logsys.mapper.db02.DB02Mapper;
import com.tx.logsys.mapper.primary.UserMapper;
import com.tx.logsys.pojo.User;
import com.tx.logsys.restbean.CommonResponse;
import com.tx.logsys.util.WmiService;
import lombok.Data;
import org.jinterop.dcom.common.JIException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Data
@RestController
@ConfigurationProperties(prefix = "sv")
@RequestMapping("/windows")
public class WindowsControl {

    private static Logger logger = LoggerFactory.getLogger(WindowsControl.class);

    // windows 配置信息
    private List<Map<String, String>> wins;

    // dbsNav
    @Value("${dbsNav}")
    String dbsNav;

    @Value("${SourceName}")
    String SourceName;

    @Autowired
    UserMapper userMapper;

    @Autowired
    DB02Mapper DB02Mapper;

    @Autowired
    DB02Mapper DB03Mapper;

//    @Autowired
    DB02Mapper DB04Mapper;

    private int RECONNECT_TIMES = 0;// 重连次数

    @RequestMapping
    public Object index() {

//        EventLogListener.getLog();

        User user = userMapper.selectByPrimaryKey(1);
        User user1 = DB02Mapper.selectByPrimaryKey(1);

        return user;
    }

    /**
     * 获取 Nav
     *
     * @return
     */
    @PostMapping(value = "/getNav")
    public CommonResponse getNavList() {
        Map<String, Object> map = new HashMap<>();
        map.put("wins", wins);
        map.put("dbs", dbsNav.split(","));
        return new CommonResponse<>(map);
    }

    /**
     * 获取日志
     *
     * @return
     */
    @RequestMapping(value = "/getList")
    public CommonResponse getList(
            @RequestParam(defaultValue = "1") int pageNum,
            @RequestParam(defaultValue = "10") int pageSize,
            @RequestParam(required = false) String search,
            @RequestParam(defaultValue = "0") int logType
    ) {

        RECONNECT_TIMES = 0;// 重连次数

        Map<String, String> v = wins.get(logType);

        String domain = v.get("domain");
        String host = v.get("host");
        String user = v.get("user");
        String password = v.get("password");

        logger.info("domain >>> {}, host >>> {},  user >>> {}, password >>> {}", domain, host, user, password);

        WmiService wmiService = getWmiService(domain, host, user, password);

//        WmiService wmiService = new WmiService(host);
        //域（一般为空字符），用户名，密码
//        wmiService.connect(domain, user, password);

        logger.info("连接成功 wmiService >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> {}", wmiService);
//        String strQuery = "SELECT * FROM Win32_NTLogEvent WHERE Logfile = 'Application' AND SourceName = 'ESENT'";
        String strQuery = "SELECT * FROM Win32_NTLogEvent WHERE Logfile = 'Application' AND SourceName = '" + SourceName + "'";
        List<Map<String, Object>> list = wmiService.query(strQuery);

        return new CommonResponse<>(list);

    }

    public WmiService getWmiService(String domain, String host, String user, String password) {
        WmiService wmiService = new WmiService(host);
        try {
            //域（一般为空字符），用户名，密码
            wmiService.connect(domain, user, password);
        } catch (JIException e) {
            e.printStackTrace();
            if (RECONNECT_TIMES < 5) {// 尝试重连，尝试次数 5
                RECONNECT_TIMES++;
                logger.info(" *************** RECONNECT_TIMES, {} times *************** ", RECONNECT_TIMES);// 连接异常尝试重连
                try {
                    Thread.sleep(1000);
                    return getWmiService(domain, host, user, password);
                } catch (InterruptedException ex) {
                    ex.printStackTrace();
                }
            }
        }
        return wmiService;
    }

    /**
     * 获取DB日志
     *
     * @return
     */
    @PostMapping(value = "/getDbLogList")
    public CommonResponse getDbLogList(
            @RequestParam(defaultValue = "1") int pageNum,
            @RequestParam(defaultValue = "10") int pageSize,
            @RequestParam(required = false) String search,
            @RequestParam(required = false) String search1,
            @RequestParam(required = false) String status,
            @RequestParam(required = false) String startTime,
            @RequestParam(required = false) String endTime,
            @RequestParam(defaultValue = "1") String dbType,
            @RequestParam(defaultValue = "1") String sqlType
    ) {

        Map<String, Object> map = new HashMap<>();
        map.put("search", search);
        map.put("search1", search1);
        map.put("status", status);
        map.put("startTime", startTime);
        map.put("endTime", endTime);

        PageHelper.startPage(pageNum, pageSize);

        // 获取 mapper
        BaseUserMapper baseUserMapper = getUserMapper(dbType);

        List<Map<String, Object>> list = null;
        switch (sqlType) {
            case "1":// 流程报错日志
                list = baseUserMapper.Orchestration(map);
                break;
            case "2":// 发送端口报错日志
                list = baseUserMapper.SendPort(map);
                break;
            case "3":// 接受端口报错日志
                list = baseUserMapper.ReceivePort(map);
                break;
            case "4":// 其它
                list = baseUserMapper.Isolated(map);
                break;
            case "5":// 新增查询所有成功调用流程的sql
                list = baseUserMapper.QueryAllCompleted(map);
                break;
            case "6":// 查询所有传入传出的状态的Sql
                list = baseUserMapper.QueryAllMessage(map);
                break;
        }

        PageInfo<Map<String, Object>> pageInfo = new PageInfo<>(list);

        return new CommonResponse<>(pageInfo);
    }

    /**
     * 获取 mapper
     *
     * @param type
     * @return
     */
    public BaseUserMapper getUserMapper(String type) {
        switch (type) {
            case "0":
                return userMapper;
            case "1":
                return DB02Mapper;
            case "2":
                return DB03Mapper;
            case "3":
                return DB04Mapper;
            default:
                return null;
        }
    }


}
